#!/bin/sh
# Bug reports and comments to Igor.Ermolaev@intel.com
unset opr
if   [ "$1" == abs  ]; then
   opr='+'
elif [ "$1" == rel  ]; then
   opr='-'
elif [ "$1" == base ]; then
   opr='='
else
   exit 1
fi
shift

modl="$1";shift
ladr=`echo "$modl"|sed -n 's/^.*[+:]\(\(0x\)\?\([0-9A-Fa-f]\+\)\)$/\1/p'`
if [ -n "$ladr" ]; then modl="${modl%[+:]*}"; fi

if [ "$TRACING_SDK_ADDR_MODE" != rel ]; then
   unset ladr
elif [ -z "$ladr" ]; then
   if [ -x "$modl" ]; then
      ladr=`readelf -l "$modl"|grep -B 1 '\sR\s\+E\s'|grep -m 1 LOAD|awk '{print $3}'|sed 's/\(0x\)\?0*\([0-9A-Fa-f]\+\)/\1\2/'`
   else
      unset ladr
   fi
fi

if [ "$opr" == '=' ]; then
   echo "$modl${ladr:++$ladr}";exit 0
elif [ "${ladr:0:2}" == 0x ]; then
   ladr=`echo $ladr|tr '[:lower:]' '[:upper:]'`
   ladr=`echo "ibase=16;${ladr#0X}"|bc`
fi
sep=''
process()
{
   if [ -z "$ladr" ]; then echo -n "$1";return; fi
   eval data=( `echo "$1"|sed -n 's/^\(0x\)\?\([0-9A-Fa-f]\+\)\(.*\)$/'"'"'\1'"'"' '"'"'\2'"'"' '"'"'\3'"'"'/p'` )
   echo -n "$sep";sep=' '
   if [ -z "${data[1]}" ]; then
      echo -n "$1"
   else
      if [ "${data[0]}" == 0x ]; then nbase=16; else nbase=10; fi
      addr=`echo "${data[1]}"|tr '[:lower:]' '[:upper:]'`
      addr=`echo "t=$ladr;obase=$nbase;ibase=$nbase;$addr${opr}t"|bc|tr '[:upper:]' '[:lower:]' `
      if [ "${addr:0:1}" == '-' ]; then data[0]="-${data[0]}"; addr=${addr#-}; fi
      echo -n "${data[0]}$addr${data[2]}"
   fi
} 
if [ -n "$1" ]; then
   while [ -n "$1" ]; do
      process "$1";shift
   done
   echo
else
   while read line; do
      for f in $line; do
         process "$f"
      done
      echo
   done
fi
